function loadImage(url) {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.src = url
    img.onload = function() {
      resolve(img)
    }
    img.onerror = function() {
      reject('读取图片失败')
    }
  })
}

function render(game, el) {
  const canvas = document.createElement('canvas')
  canvas.width = game.mapWidth
  canvas.height = game.mapHeight
  canvas.className = 'map'
  canvas.style.border = "1px dashed lightgray"
  el.appendChild(canvas)
  const ctx = canvas.getContext('2d')
  const {player, monster} = game
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  const resourceLoaded = Promise.all([
    loadImage('images/monster.png'),
    loadImage('images/player.png'),
    loadImage('images/star.png'),
    loadImage('images/background.jpg'),
  ])
  .then(imgRes => {
    drawAnimation(imgRes)
  }, err => {
    alert(err)
    throw Error(err)
  })

  function drawMob(ctx, img, moveable) {
    if(typeof moveable.rotateDeg !== 'undefined'){
      let tX, tY, rotateArc
      tX = moveable.x + moveable.width / 2
      tY = moveable.y + moveable.height / 2
      rotateArc = moveable.rotateDeg * Math.PI / 180
      ctx.translate(tX, tY)
      ctx.rotate(rotateArc);
      ctx.drawImage(img, - moveable.width / 2, - moveable.height / 2, moveable.width, moveable.height);
      ctx.rotate(-rotateArc);
      ctx.translate(-tX, -tY)
    }else {
      ctx.drawImage(img, moveable.x, moveable.y, moveable.width, moveable.height);
    }
    if([1,2].includes(moveable.type)) {
      ctx.fillStyle = "#ff0000"
      ctx.fillRect(moveable.x, moveable.y, moveable.width, 5);
      const percent = moveable.hits / moveable.hits_max;
      ctx.fillStyle = "#32cd32"
      ctx.fillRect(moveable.x, moveable.y, moveable.width * percent, 5);
    }
  }

  let offsetX = 0;
  function drawBackground(ctx, img) {
    const {mapWidth, mapHeight} = game;
    // 背景实际上是用同一张图片绘制两次拼接成的
    // 通过改变两个图片在可见区域中所占的比例，就形成了背景滚动
    ctx.drawImage(img, -offsetX, 0, mapWidth, mapHeight);
    ctx.drawImage(img, mapWidth - offsetX - 1, 0, mapWidth, mapHeight);
    offsetX += game.bgSpeed;
    if(offsetX >= mapWidth) {
      offsetX = 0;
    }
  }

  function drawAnimation([monsterPic, playerPic, starPic, bgPic]) {
    let time = 0
    function drawGame() {
      let timeNow = Date.now()
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      drawBackground(ctx, bgPic)
      if(time) {
        let fps = (1000 / (timeNow - time)).toFixed(0);
        ctx.font = '20px Verdana'
        ctx.fillStyle = '#ff0000'
        ctx.fillText(`FPS: ${fps}`, 0, 15);
      }
      drawMob(ctx, monsterPic, monster);
      drawMob(ctx, playerPic, player);
      monster.projectiles.forEach(projectile => {
        drawMob(ctx, starPic, projectile)
      })
      player.projectiles.forEach(projectile => {
        drawMob(ctx, starPic, projectile)
      })
      time = timeNow;
      requestAnimationFrame(drawGame)
    }
    requestAnimationFrame(drawGame)
  }
}
